﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace CSM_SQL.DAL
{


    public class CustomerDAL
    {
        private CSMDataBaseDataContext _data;

        private CSMDataBaseDataContext Data
        {
            get
            {
                if (_data == null || !_data.DatabaseExists())
                    _data = new CSMDataBaseDataContext(ConfigurationManager.ConnectionStrings["Constr"].ToString());
                return _data;
            }
        }

        internal Boolean Insert(Customer c)
        {
            try
            {
                Data.Customer.InsertOnSubmit(c);
                Data.SubmitChanges();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return true;
        }

        internal List<Customer> All()
        {
            //var a = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString.ToString();

            //ConnectionStringSettings mySettings =
            //new ConnectionStringSettings("qqq", "qqqqq", "fasfsfa");
            //ConnectionStringsSection c = new ConnectionStringsSection();
            //Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //c.AppSettings.Settings.Add("hello", "hello world");
            //c.ConnectionStrings.ConnectionStrings.Add(mySettings);


            //var r = Properties.Settings.Default.SuperMarketConnectionString;
            //var q = ConfigurationManager.AppSettings;

            //var z = ConfigurationManager.ConnectionStrings;

            // CSMDataBaseDataContext data = new CSMDataBaseDataContext(r);
            return Data.Customer.ToList<Customer>();
        }

        internal Boolean ChangeState(int id, int state)
        {
            try
            {
                
                //var cc = (from c in Data.Customer where c.C_ID == id select c.State);
                //var z = cc.ToList();
                //z[0] = state;

                (from c in Data.Customer where c.C_ID == id select c).ToList()[0].State = state;
                Data.SubmitChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

        /// <summary>
        /// 返回用户的全部订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        internal List<Cus_Ord> GetOrder(int C_ID)
        {
            List<Cus_Ord> orders = new List<Cus_Ord>();
            var order = from o in Data.Order join g in Data.Goods on o.G_ID equals g.G_ID where C_ID == o.C_ID && o.State < 3  join c in Data.Customer on o.C_ID equals c.C_ID select new { o, g, c };

            foreach (var o in order)
            {
                OrderMes ord = new OrderMes { order = o.o, goods = o.g, customer = o.c };
                if (ord.order.State > 0)
                {
                    if (ord.order.Temp != 0)
                    {
                        var poster = (from p in Data.Customer join oo in Data.Order on p.C_ID equals oo.C_ID select p).First();
                        ord.postName = poster.Name;
                        ord.postPhone = poster.Phone;
                    }
                    else
                    {
                        var poster = (from p in Data.Emp join oo in Data.Order on p.E_ID equals oo.C_ID select p).First();
                        ord.postName = poster.Name;
                        ord.postPhone = poster.Phone;
                    }
                }
                var eo = ord.TransCusOrd();
                if (o.o.State >= 3)
                {
                    var assess = (from a in Data.Assess where a.ID == o.o.ID select a).First();
                    eo.grade = assess.Grade;
                    eo.assess = assess.Assess1;
                }
                orders.Add(eo);
            }
            return orders;
        }

        internal List<OrderMes> GetTasks(int id)
        {
            List<OrderMes> list = new List<OrderMes>();
            var order = from o in Data.Order join g in Data.Goods on o.G_ID equals g.G_ID  join c in Data.Customer on o.C_ID equals c.C_ID where o.State == 0 || (o.Temp == 1 && o.TransID == id) join a in Data.Assess on o.ID equals a.ID into q  from qqq in q.DefaultIfEmpty() select new { o, g, c,a = qqq };

            foreach (var o in order)
            {
                OrderMes ord = new OrderMes { order = o.o, goods = o.g, customer = o.c ,assess=o.a};
                list.Add(ord);
            }
            return list;
        }

        internal List<CartMes> GetCart(int id)
        {
            List<CartMes> list = new List<CartMes>();
            foreach(var c in from c in Data.Cart join g in Data.Goods on c.G_ID equals g.G_ID where c.C_ID == id select new {c,g })
            {
                CartMes a = new CartMes { goods = c.g, cart = c.c };
                list.Add(a);
            }
            return list;

        }

        internal Boolean DelCart(int id)
        {

            try
            {
                var d = Data.Cart.Where(a => a.Car_ID == id);
                Data.Cart.DeleteAllOnSubmit(d);
                Data.SubmitChanges();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return true;
        }

        internal Boolean ClearCart(int id)
        {

            try
            {
                var d = Data.Cart.Where(a => a.C_ID == id);
                Data.Cart.DeleteAllOnSubmit(d);
                Data.SubmitChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

        internal void ChangeCart(int id,int num)
        {
            var cart = Data.Cart.Where(a => a.Car_ID == id).First();
            cart.amount = num;
            try {

                Data.SubmitChanges();
            } catch(Exception ex)
            {
                throw ex;
            }
        }

        internal Boolean Pay(int[] ids)
        {
            try
            {
                foreach (var id in ids)
                {
                    var car = Data.Cart.Where(c => c.Car_ID == id).First();
                    if (car != null)
                    {
                        var newOrd = new Order
                        {
                            C_ID = car.C_ID,
                            G_ID = car.G_ID,
                            Amount = car.amount,
                            Temp = 0,
                            TransID = null,
                            State = 0
                        };
                        var a = Data.Goods.Where(g => g.G_ID == car.G_ID).First();
                        if(a.Stock -car.amount >= 0)
                        {
                            var date = DateTime.Now.Date;
                            if (Data.Income.Where(d => d.Date == date).Count() > 0)
                                Data.Income.Where(d => d.Date == date).First().Income1 += (car.amount * a.Price);
                            else
                            {
                                Income inc = new Income
                                {
                                    Date = date,
                                    Income1 = (car.amount * a.Price)
                                };
                                Data.Income.InsertOnSubmit(inc);
                            }
                            a.Stock -= car.amount;
                            newOrd.StartTime = DateTime.Now.ToUniversalTime();
                            newOrd.EndTime = null;
                            newOrd.TempTime = null;
                            Data.Cart.DeleteOnSubmit(car);
                            Data.Order.InsertOnSubmit(newOrd);
                            Data.SubmitChanges();
                        }
                        
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

        internal Boolean Apply(int O_id,int T_id)
        {
            try
            {
                var ord = Data.Order.Where(o => o.ID == O_id).First();
                ord.Temp = 1;
                ord.TransID = T_id;
                Data.SubmitChanges();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return true;
        }

        internal void Send(int id)
        {
            Data.Order.Where(a => a.ID == id).First().State++;
            Data.SubmitChanges();
        }

        internal int Pick(int C_ID,int G_ID)
        {
            if(Data.Cart.Where(a=>a.C_ID==C_ID&&a.G_ID==G_ID).Count()>0)
            {
                return Data.Cart.Where(c => c.C_ID == C_ID).Count();
            }
            Cart cart = new Cart
            {
                C_ID = C_ID,
                G_ID = G_ID,
                amount = 1
            };

            Data.Cart.InsertOnSubmit(cart);
            Data.SubmitChanges();
            return Data.Cart.Where(c => c.C_ID == C_ID).Count();
        }

        internal List<OrderMes> GetHistory(int C_ID)
        {
            List<OrderMes> list = new List<OrderMes>();
            var order = from o in Data.Order join g in Data.Goods on o.G_ID equals g.G_ID where o.C_ID == C_ID join a in Data.Assess on o.ID equals a.ID into q from qqq in q.DefaultIfEmpty() select new { o, g, a = qqq  };
            foreach (var o in order)
            {
                var ord = new OrderMes
                {
                    order = o.o,
                    goods = o.g,
                    assess = o.a
                };
                if (ord.order.State > 0)
                {
                    if (ord.order.Temp == 1)
                    {
                        var poster = Data.Customer.Where(a => a.C_ID == ord.order.TransID).First();
                        ord.postName = poster.Name;
                        ord.postPhone = poster.Phone;
                    }
                    else
                    {
                        var poster = (from p in Data.Emp join oo in Data.Order on p.E_ID equals oo.C_ID select p).First();
                        ord.postName = poster.Name;
                        ord.postPhone = poster.Phone;
                    }
                    
                }
                list.Add(ord);
            }
            return list;
        }

        internal void Sign(int id)
        {
            try
            {
                var ord = Data.Order.Where(o => o.ID == id).First();
                ord.State = 3;
                ord.EndTime = DateTime.Now;
                Data.SubmitChanges();
            }
            catch(Exception ex)
            {
                throw ex;
            }

            
        }

        internal Boolean PostAssess(Assess a)
        {
            try
            {
                Data.Assess.InsertOnSubmit(a);
                Data.SubmitChanges();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return true;
        }

        internal bool Edit(Customer c)
        {
            try
            {
                var a = Data.Customer.Where(q => q.C_ID == c.C_ID).First();
                a.Phone = c.Phone;
                a.Address = c.Address;
                Data.SubmitChanges();
            }
            catch (Exception ex)
            {

            }
            return true;
        }

        internal bool ChangePwd(Customer c)
        {
            try
            {
                var a = Data.Customer.Where(q => q.C_ID == c.C_ID).First();
                a.Password = c.Password;
                Data.SubmitChanges();
            }
            catch (Exception ex)
            {

            }
            return true;
        }
    }

    
}
